import {chooseCard} from '../../../assets/js/toonModule.js'
import util from '../../../assets/js/util'
import Toast from 'toon-ui/lib/components/toast'


export default {
  data() {
    return {
      detailData: {
        "subjectName": "", //专题名称
        "content": false, //内容
        "photos": [],  // 图片
        "createDate": "", // 创建时间
        "praised": true,  // 是否被赞过
        "praiseCount": 0,  // 赞数
        "commentCount": 0, // 评论数
        "auditCode":0
      },
      showComment: false, // 显示评论
      commentList: [], // 评论列表
      content:'', //评论内容
      curPage: 0,
      pageNum: '1',  //当前页
      pageSize: '10', // 每页个数
      isShowContent: false, // 显示详情状态,
      alert: false // 键盘弹出状态
    }
  },
  filters: {
    thumbnail: function (url, param) {
      return url.replace(".png", param + ".png").replace(".jpg", param + ".jpg")
    },
    "changeTimeYMD": function (value) {
      return value;
      //return util.dateFormat('yyyy-MM-dd', value)
    },
    "changeTimeHM": function (value) {
      return value;
      //return util.dateFormat('hh:mm', value)
    },
    /**
     * 0 => 赞
     */
    changeVote: function (num) {
      return num > 0 ? num  > 9999 ? (num/10000).toFixed(1).replace('.0', '') + 'W' : num : '赞'
    },
    /**
     * 0 => 评论
     */
    changeDis: function (num) {
      return num > 0 ? num  > 9999 ? (num/10000).toFixed(1).replace('.0', '') + 'W' : num : '评论'
    },
  },
  mounted() {
    let _this = this;
    this.init();
    let type = this.$util.sessionData('tabkey');
    // this.$util.setTitle('我的随手拍');
  },
  beforeRouteLeave(to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
    // this.$util.droploadUpOnScroll()
    let counts ={
      index:this.$route.query.index,
      id : this.$route.params.id,
      praiseCount:0,
      commentCount:0,
      auditCode:0,
    };

    counts.praiseCount = this.detailData.praiseCount;
    counts.commentCount = this.detailData.commentCount;
    counts.praised = this.detailData.praised;
    counts.auditCode = this.detailData.auditCode;
    this.$util.sessionData('counts',JSON.stringify(counts));
    if(this.$util.sessionData('readStatus') != null){
      let statusObj= JSON.parse(this.$util.sessionData('readStatus'));
      statusObj.haveSeen = true;
      this.$util.sessionData('readStatus',JSON.stringify(statusObj));
    }
    next();
  },
  //销毁实例
  deactivated(){
    this.$destroy();
  },
  methods: {
    init() {
      // 初始化
      this.curPage = 0;
      this.pageNum = 1; //当前页
      this.pageSize = 10; // 每页个数
      this.content = '';
      this.ShowContent = false;
      // 清除评论
      this.commentList = [];
      // 获取详情
      this.getDetailById();

    },
    /**
     * 获取详情
     */
    getDetailById() {
      let _this = this;
      let id = _this.$route.params.id;
      let index = _this.$route.query.index;
      let params = {
        "id": id
      };
      this.$http.post('/convphoto/queryPhotoDetailById', params).then(function (rep) {
        if (rep.meta && rep.meta.code == '0') {

          if (rep.data && rep.data.dealProcess) {
            _this.$router.replace({
              name: "detailReport",
              params: { id: params.id },
              query: {index:index}
            });
          }
          // 详情数据的替换
          _this.detailData = rep.data;
          _this.detailData.content = _this.detailData.content.replace(/\n/g, "<br>");
          // 判断随手拍类型
          if(_this.detailData.convType == 1) {
            _this.$util.setTitle('最美门城');
          } else if(_this.detailData.convType == 3) {
            _this.$util.setTitle('社会警示');
          }else if(!_this.detailData.convType){
            _this.$util.setTitle('我的随手拍');
          }
          // 显示详情
          _this.isShowContent = true;
          // 获取评论列表
          _this.getCommentListById();
          // if (_this.detailData.commentCount && _this.detailData.commentCount > 0) {

          // }
        }else {
          Toast({
            'message': rep.meta.message,
            'duration': 1000, // 持续时间，默认3000毫秒
          });
        }
      }).catch(function (err) {
        // Toast({
        //   'message': '获取详情失败',
        //   'duration': 1000, // 持续时间，默认3000毫秒
        // });
      })
    },
    /**
     * 获取评论列表
     */
    getCommentListById() {
      let _this = this;
      let id = _this.$route.params.id
      if (_this.curPage == _this.pageNum) {
        return
      } else {
        _this.curPage = _this.pageNum
      }

      let params = {
        "id": id,
        "pageNum": _this.pageNum,
        "pageSize": _this.pageSize
      }
      _this.$http.post('/praisingCity/queryCommentListById', params, {loading: false}).then(function (rep) {
        if (rep.meta && rep.meta.code == '0') {
          _this.showComment = true;
          //
          if (rep.data.length > 0) {
            _this.commentList = _this.commentList.concat(rep.data);
            console.log( _this.commentList)
          }
          //
          if (rep.data.length == _this.pageSize) {
            _this.$util.droploadUpOnScroll({ ele: 'mainScroll' }, _this.getCommentListById)
            _this.pageNum++;
          }else {
            _this.$util.droploadUpOnScroll({ ele: 'mainScroll', stop: true, text: ' '})
          }

        }



      }).catch(function (err) {
        console.log(err)
      })
    },
    /**
     * 名片跳转
     */
    goFrame(feedId) {
      let params = {
        'feedId': feedId,
      }
      window.location.href = 'toon://frame?params=' + JSON.stringify(params)
    },
    /**
     * 点赞
     */
    praise() {
      if (!this.toonNETWORK()) { return }
      let _this = this;
      let id = _this.$route.params.id
      let params = {
        'id': id
      }
      this.$http.post('/praisingCity/praise', params, { loading: false }).then(function (rep) {
        _this.detailData.praised = !_this.detailData.praised;
        console.log(_this.detailData.praised)
        if (_this.detailData.praised) {
          _this.detailData.praiseCount = _this.detailData.praiseCount - 0 + 1;
        } else {
          _this.detailData.praiseCount = _this.detailData.praiseCount - 0 - 1;
        }
        console.log(JSON.stringify(_this.detailData, null, 2))
      }).catch(function (err) {
        console.log(err)
      })
    },
    /**
     * 无网判断
     */
    toonNETWORK() {
      if (navigator.onLine) {
        return true
      }
      Toast({
        message: '无网络链接',
        duration: 1000, // 持续时间，默认3000毫秒
      });
      return false
    },
    /**
     * 提交评论
     */
    addComment() {
      if (!this.toonNETWORK()) { return }
      let _this = this;
      let id = _this.$route.params.id;
      let content = _this.content.trim();
      // 内容为空
      if (content == '' || !content) {
        Toast({
          'message': '评论内容不能为空',
          'duration': 2000
        })
      }else if(content.trim().length > 140) {
        Toast({
          'message': '评论内容不能超过140字',
          'duration': 2000
        })
      } else {
        _this.choose(function (userInfo) {
          // 如果点击取消
          if (userInfo.data.result == 'cancel') {

          } else {
            let params = {
              "commentAvator": userInfo.data.avatarId,
              "commentName": userInfo.data.title,
              "content": content,
              "feedId": userInfo.data.feedId,
              "id": id
            }
            _this.$http.post('/praisingCity/addComment', params).then(function (rep) {
              if (rep.meta && rep.meta.code == '0') {
                _this.showComment = false;
                _this.init();
              }else {
                Toast({
                  'message': '评论失败',
                  'duration': 2000
                })
              }
            }).catch(function (err) {
              Toast({
                'message': '评论失败',
                'duration': 2000
              })
            })
          }

        });
      }
    },
    choose(callback) {
      let _this = this;
      chooseCard(function (data) {
        callback(data);
      })
    },
    /**
     * 键盘弹起状态
     * @param {*} bool
     */
    textFoucs(bool) {
      let _this = this;
      let scrollTop = 0;
      _this.alert = bool;
      var newContent = this.content.replace(/[*]/g,'-').replace(/[\n\r]/g,'**');
      if(newContent.length>140){
        newContent = newContent.substring(0,140);
        newContent = newContent.replace(/\*\*/g,'-').replace(/\*$/,'');
        this.content = this.content.substring(0,newContent.length);
      }
      // if(bool) {
      //   console.log(scrollTop)
      //     this.$refs.submitText.scrollTop  = scrollTop;
      // }else {
      //   scrollTop = this.$refs.submitText.scrollTop;
      //   this.$refs.submitText.scrollTop = 0;
      // }
    },
    /**
     * 跳转专题详情页
     */
    goSubject(subjectId){
      this.$router.push({'name':'subjectList',params: { 'subjectId': subjectId }})
    },

  },
  components: {

  }
}
